package com.iris.live.services.services.impl;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.iris.live.services.common.NumberUtils;
import com.iris.live.services.common.config.Constants;
import com.iris.live.services.common.reconsitution.CollectionUtils;
import com.iris.live.services.covervo.CustomCarCovert;
import com.iris.live.services.covervo.CustomCarDetailCover;
import com.iris.live.services.data.models.CustomCarConfigureDetailModel;
import com.iris.live.services.data.models.CustomCarConfigureModel;
import com.iris.live.services.data.models.Lsh库存表Model;
import com.iris.live.services.data.models.PermitCodeModel;
import com.iris.live.services.data.repositories.*;
import com.iris.live.services.requestbody.CustomCarConfigureDetailBody;
import com.iris.live.services.services.AfterMarketService;
import com.iris.live.services.services.ICustomCarConfigureDetailService;
import com.iris.live.services.vo.aftermarket.AfterMarketObj;
import com.iris.live.services.vo.aftermarket.AfterMarketRows;
import com.iris.live.services.vo.aftermarket.QuoteAfterSalesInfo;
import com.iris.live.services.vo.customcarconfigure.CustomConfigureDetailPreviewVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * y
 */
@Service
public class CustomCarConfigureDetailServiceImpl implements ICustomCarConfigureDetailService{

    private static Logger logger = LoggerFactory.getLogger(CustomCarConfigureDetailServiceImpl.class);

    @Autowired
    private ICustomCarConfigureDetailRepository customCarConfigureDetailRepository;

    @Autowired
    private ICustomCarConfigureRepository customCarConfigureRepository;

    @Autowired
    private ICustomCarConfigureJpaRepository iCustomCarConfigureJpaRepository;

    @Autowired
    private ICustomCarConfigureDetailJpaRepository iCustomCarConfigureDetailJpaRepository;

    @Autowired
    private Lsh库存表Repository stockRepository;

    @Autowired
    private 报价单表Repository orderRepository;

    @Autowired
    private AfterMarketService afterMarketService;


    /**
     * 精品总价计算公式
     * @param price
     * @param num
     * @param discount
     * @return
     */
    public static Float countPrice(Float price,Integer num,Float discount){
        Float totalPrice = 0.00F;
        if (discount <= 0.00F){//折扣率小于等于0返回原价
            totalPrice = price * num;
        }else{
            totalPrice = (price * num) * discount;
        }
        return totalPrice;
    }

    /**
     * 保存加配
     * @param list
     * @param storeIds
     * @throws Exception
     */
    @Override
    @Transactional(propagation= Propagation.REQUIRED,rollbackFor=Exception.class)
    public void insertBatch(List<CustomCarConfigureDetailBody.DetailBody> list, String storeIds){
        try{
            //取得处理后的结果
            Map<String,Object> res = getBaseModelAndAutt(list,storeIds);
            //先存加配基本信息（批量）
            iCustomCarConfigureJpaRepository.save((List<CustomCarConfigureModel>) res.get("list"));
            //保存加配详情（批量，详情的库存ID存成string 多个用,隔开）
            iCustomCarConfigureDetailJpaRepository.save((List<CustomCarConfigureDetailModel>) res.get("detailList"));
            //更新msrp
            //choiceUpdateWay((List<CustomCarConfigureModel>) res.get("list"),null,LocalDefaultConstant.METHOD_TYPE_INSERT,null,null);
        }catch (Exception e){
            logger.error("保存加配异常",e);
        }
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED,rollbackFor=Exception.class)
    public void update(CustomCarConfigureDetailBody.DetailBody model, Integer detailId){
        try{
            CustomCarConfigureDetailModel detailModel = iCustomCarConfigureDetailJpaRepository.getCustomCarConfigureDetailModelById(detailId);
            if (null != detailModel){
                //取得原先子项的应收总计 和实收总计
                Float orgTotalPrice = detailModel.getNetReceipts();//应收总计
                Float orgFactPrice = detailModel.getReceivable();//实收总计
                //先更新子项 精品个数 boutiqueNum、折扣率 discount、应收价格 receivable、实际价格 netReceipts
                Float totalPriceSub = 0.00F;//应收总计差额
                Float factPriceSub = 0.00F;//实收总计差额
                Float currTotalPrice = countPrice(model.boutiquePrice,model.boutiqueNum,0.00F);
                Float currFactPrice = countPrice(model.boutiquePrice,model.boutiqueNum,model.discount);
                detailModel.setReceivable(currTotalPrice);//应收总计
                detailModel.setNetReceipts(currFactPrice);//折后实收总计
                detailModel.setBoutiqueNum(model.boutiqueNum);
                detailModel.setDiscount(model.discount);
                iCustomCarConfigureDetailJpaRepository.save(detailModel);

                //定位父及
                List<Map> org =  customCarConfigureRepository.findByStoreId(String.valueOf(detailModel.getStoreId()),CustomCarConfigureModel.STATUS_YES,model.permit);
                //父级总计减
                if(orgTotalPrice > currTotalPrice){
                    //重新计算父级金额
                    totalPriceSub = orgTotalPrice - (orgTotalPrice - currTotalPrice);
                    factPriceSub = orgFactPrice - (orgFactPrice - currFactPrice);
                    //加
                }else if(orgTotalPrice < currTotalPrice){
                    totalPriceSub = orgTotalPrice + (currTotalPrice - orgTotalPrice);
                    factPriceSub = orgFactPrice + (currFactPrice - orgFactPrice);
                }
                if(null  != org && org.size() >0){
                    CustomCarConfigureModel cus = CustomCarCovert.queryMapConvertModel(org);
                    Double cusorgFactPrice = cus.getFactPrice();
                    cus.setFactPrice(factPriceSub.doubleValue());
                    cus.setTotalPrice(totalPriceSub.doubleValue());
                    iCustomCarConfigureJpaRepository.save(cus);
                    //更新MSRP
                    //choiceUpdateWay(null,cus.getStoreId(), LocalDefaultConstant.METHOD_TYPE_UPDATE,NumberUtils.getBigDecimalValue(String.valueOf(cusorgFactPrice)),NumberUtils.getBigDecimalValue(String.valueOf(cus.getFactPrice())));
                }
            }
        }catch (Exception e){
            logger.error("更新加配异常",e);
        }
    }

    /**
     * 删除加配
     * @param storeId
     * @param detailId
     */
    @Override
    @Transactional(propagation= Propagation.REQUIRED,rollbackFor=Exception.class)
    public void deleteFalse(String storeId, String detailId,String permit){
        try{
            //取出加配详情便利库存ID
            CustomCarConfigureDetailModel model = iCustomCarConfigureDetailJpaRepository.getCustomCarConfigureDetailModelById(Integer.parseInt(detailId));
            if (null != model){
                deleteResult(model,storeId,permit);
            }
        }catch (Exception e){
            logger.error("删除加配",e);
        }
    }

    @Override
    public boolean isConfigure(Integer storeId) {
        boolean result = false;
        //当前库存是否未卖
        Lsh库存表Model stockModel = stockRepository.findLshStockByStockId(storeId);
        //当前库存是否未被挂车
       /* List<报价单表Model> list = orderRepository.getListByStockId(storeId);  注掉此段是因为 bug 6635
         ("未卖".equals(stockModel.get车辆零售状态()) && list.size() == 0 ){*/
        if ("未卖".equals(stockModel.get车辆零售状态()) && stockModel.get报价编号()==null){
            result = true;
        }
        return result;
    }

    @Override
    public List<QuoteAfterSalesInfo> getCarConfigureAfterMarket(String vin,String permit) {
        List<QuoteAfterSalesInfo> list = new ArrayList<QuoteAfterSalesInfo>();
        //查询当前VIN码对应的库存ID
        Lsh库存表Model stockModel = stockRepository.findLshRecordByVin(vin);
        if(stockModel != null){
            //查询是否有过加配
            List<Map<String,String>>  customList =  customCarConfigureDetailRepository.findListByStoreId(String.valueOf(stockModel.get库存编号()),1);
            list = buildCurList(customList,permit);
        }
        return list;
    }

    @Override
    public List<CustomConfigureDetailPreviewVo> findMarketByVin(String vin, Integer status) {
        List<CustomCarConfigureDetailModel> list = new ArrayList<CustomCarConfigureDetailModel>();
        //查询当前VIN码对应的库存ID
        Lsh库存表Model stockModel = stockRepository.findLshRecordByVin(vin);
        if(stockModel != null){
            //查询是否有过加配
            list =  iCustomCarConfigureDetailJpaRepository.findMarketByVin(stockModel.get库存编号(),1);
        }
        return CustomCarDetailCover.getDetailPreviewList(list);
    }

    @Override
    public List<CustomCarConfigureDetailModel> findByCustomCarId(Integer customCarId, Integer status){
        return customCarConfigureDetailRepository.findByCustomCarId(customCarId,status);
    }


    //内部调用模块

    @Override
    public   List<Map<String,String>> findListByStoreId(String storeId, Integer status){
        return customCarConfigureDetailRepository.findListByStoreId(storeId,status);
    }

    /**
     * 赋值部分属性
     * @param list
     * @param storeIds
     * @return
     */
    private Map<String,Object> getBaseModelAndAutt(List<CustomCarConfigureDetailBody.DetailBody> list, String storeIds) throws Exception{
        Map<String,Object> res = Maps.newHashMap();
        //便利取得每个详情对象计算单个的价格、以及取得每个库存对应的总价
        Float totalPrice = 0.00F;
        Float factPrice = 0.00F;
        List<String> storeIdList = CollectionUtils.ArrToCollection(storeIds.split(CollectionUtils.SPLIT_STR_STRING));//分割ID集合
        //
        String permit =null;
        List<CustomCarConfigureDetailModel> listDetail =  new ArrayList<CustomCarConfigureDetailModel>();
        for (String storeId:storeIdList) {
            for (CustomCarConfigureDetailBody.DetailBody  body : list) {
                if(null != body){
                    CustomCarConfigureDetailModel baseModel = new CustomCarConfigureDetailModel();
                    Float currTotalPrice = countPrice(body.boutiquePrice,body.boutiqueNum,0.00F);
                    Float currFactPrice = countPrice(body.boutiquePrice,body.boutiqueNum,body.discount);
                    baseModel.setReceivable(currTotalPrice);//应收总计
                    baseModel.setNetReceipts(currFactPrice);//折后实收总计
                    baseModel.setStatus(CustomCarConfigureModel.STATUS_YES);
                    baseModel.setBoutiqueNum(body.boutiqueNum);
                    baseModel.setStoreId(Integer.parseInt(storeId));
                    baseModel.setDiscount(body.discount);
                    baseModel.setCustomName(body.customName);
                    baseModel.setBoutiqueId(body.boutiqueId);
                    baseModel.setBoutiquePrice(body.boutiquePrice);
                    baseModel.setCreatedTime(new Date());
                    baseModel.setProductNum(body.productNum);
                    baseModel.setBoutiqueName(body.boutiqueName);
                    baseModel.setClassifyId(body.classifyId);
                    baseModel.setTypeId(body.typeId);
                    //计算自定义加配应收总计
                    totalPrice = totalPrice + currTotalPrice;
                    //计算自定义加配实收总计
                    factPrice = factPrice + currFactPrice;
                    permit = body.permit;
                    //检测是否触发状态变更
                    baseModel = detailSaveTriggerUpdate(baseModel);
                    if(null != baseModel.getId()){
                        iCustomCarConfigureDetailJpaRepository.save(baseModel);
                    }
                    listDetail.add(baseModel);
                }
            }
        }
        res.put("detailList",listDetail);
        res.put("list",getBaseModelList(listDetail,storeIds,totalPrice,factPrice,permit));
        return res;
    }

    /**
     * 构建基本加配集合
     * @param list
     * @param storeIds
     * @return
     */
    private List<CustomCarConfigureModel> getBaseModelList(List<CustomCarConfigureDetailModel> list,String storeIds,Float totalPrice,Float factPrice,String permit) throws Exception{
        List<CustomCarConfigureModel> baseModelList  = new ArrayList<CustomCarConfigureModel>();
        List<String> strList  = CollectionUtils.ArrToCollection(storeIds.split(CollectionUtils.SPLIT_STR_STRING));
        for (int i = 0; i< strList.size();i++){
            if(list.size() > 0){
                CustomCarConfigureDetailModel base = list.get(0);
                CustomCarConfigureModel newModel = new CustomCarConfigureModel();
                newModel.setPermit(permit);
                newModel.setCustomName(base.getCustomName());
                newModel.setCreatedTime(new Date());
                newModel.setStatus(CustomCarConfigureModel.STATUS_YES);
                newModel.setStoreId(Integer.parseInt(strList.get(i)));
                newModel.setTotalPrice(totalPrice.doubleValue());
                newModel.setFactPrice(factPrice.doubleValue());
                newModel.setCreatedTime(new Date());
                //检测是否触发状态变更
                newModel = baseSaveTriggerUpdate(newModel);
                baseModelList.add(newModel);
            }
        }
        return baseModelList;
    }

    /**
     * 删除级联处理
     * @param model
     * @return
     */
    private boolean deleteResult(CustomCarConfigureDetailModel model,String storeId,String permit) throws Exception {
        Boolean re = false;
        //当前库存ID加配详情是否是最后一个 是改父级状态 否减去当前子项的总计金额
        List<Map<String,String>>  list = findListByStoreId(storeId,CustomCarConfigureModel.STATUS_YES);
        List<Map> baseList = customCarConfigureRepository.findByStoreId(String.valueOf(model.getStoreId()),CustomCarConfigureModel.STATUS_YES,permit);
        if(null == baseList && baseList.size() < 0) {
            return re;
        }
        CustomCarConfigureModel org = CustomCarCovert.queryMapConvertModel(baseList);
        if (list.size() <=1){
            //更改基本信息状态
            org.setStatus(CustomCarConfigureModel.STATUS_NO);
            org.setFactPrice(0.00);
            org.setTotalPrice(0.00);
            iCustomCarConfigureJpaRepository.save(org);
        }else{
            //更改基本信息总计金额
            org.setTotalPrice(org.getTotalPrice() - model.getReceivable());
            org.setFactPrice(org.getFactPrice() - model.getNetReceipts());
            iCustomCarConfigureJpaRepository.save(org);
        }
        //更新加配详情状态
        model.setStatus(CustomCarConfigureModel.STATUS_NO);
        iCustomCarConfigureDetailJpaRepository.save(model);
        //更新MSRP
        //choiceUpdateWay(null,org.getStoreId(), LocalDefaultConstant.METHOD_TYPE_DELETE,null, NumberUtils.getBigDecimalValue(String.valueOf(model.getNetReceipts())));
        return re;
    }

    /**
     * 父级新增场景是否触发修改状态
     * @param saveModel
     * @return
     * @throws Exception
     */
    private CustomCarConfigureModel baseSaveTriggerUpdate(CustomCarConfigureModel saveModel) throws  Exception{
        List<Map> list = customCarConfigureRepository.findByStoreId(String.valueOf(saveModel.getStoreId()),CustomCarConfigureModel.STATUS_YES,saveModel.getPermit());
        if(null  == list || list.size() <= 0){
            //获取当前最新msrp值
            Lsh库存表Model stocks = stockRepository.findLshStockByStockId(saveModel.getStoreId());
            saveModel.setLastMsrp(null == stocks.get实际Msrp含税()?0.00:stocks.get实际Msrp含税().doubleValue());
            return saveModel;
        }
        CustomCarConfigureModel covertModel = CustomCarCovert.queryMapConvertModel(list);
        saveModel.setId(covertModel.getId());
        saveModel.setTotalPrice(covertModel.getTotalPrice() + saveModel.getTotalPrice());
        saveModel.setFactPrice(covertModel.getFactPrice() + saveModel.getFactPrice());
        saveModel.setId(covertModel.getId());
        saveModel.setLastMsrp(covertModel.getLastMsrp());
        if(covertModel.getStatus()== CustomCarConfigureModel.STATUS_NO){
            saveModel.setStatus(CustomCarConfigureModel.STATUS_YES);
        }
        return saveModel;
    }

    /**
     * 子级新增场景是否触发修改状态
     * @param saveModel
     * @return
     * @throws Exception
     */
    private CustomCarConfigureDetailModel detailSaveTriggerUpdate(CustomCarConfigureDetailModel saveModel) throws  Exception{
        CustomCarConfigureDetailModel model = iCustomCarConfigureDetailJpaRepository.findByStockIdAndBoutiqueId(saveModel.getBoutiqueId(),saveModel.getStoreId());
        if(null  == model){
            return saveModel;
        }
        saveModel.setId(model.getId());
        if(model.getStatus()== CustomCarConfigureModel.STATUS_NO){
            saveModel.setStatus(CustomCarConfigureModel.STATUS_YES);
        }
        return saveModel;
    }

    /**
     * MSRP选择切入口
     * @param list
     * @throws Exception
     */
    private void choiceUpdateWay(List<CustomCarConfigureModel> list,Integer stockId, int type, BigDecimal org, BigDecimal current) throws  Exception{
        //判断MSRP计算方式
        switch (type){
            case Constants.METHOD_TYPE_INSERT://新增入口(current 传入的是base中的实际值)
                for (CustomCarConfigureModel model :list) {
                    //查询库存信息
                    Lsh库存表Model stocks = stockRepository.findLshStockByStockId(model.getStoreId());
                    if (null == stocks){
                      continue;
                    }
                    updateStockMsrp(stocks,NumberUtils.add(NumberUtils.getBigDecimalValue(String.valueOf(model.getLastMsrp())),NumberUtils.getBigDecimalValue(String.valueOf(model.getFactPrice()))));
                }
                break;
            case Constants.METHOD_TYPE_UPDATE://编辑(current 传入的是base中的实际值)
                Lsh库存表Model stocks = stockRepository.findLshStockByStockId(stockId);
                if (null != stocks) {
                    if (current.doubleValue() > org.doubleValue()) {
                        //获得当前值比之前多余部分
                        BigDecimal msrp = NumberUtils.subtract(current, org);
                        updateStockMsrp(stocks, NumberUtils.add(stocks.get实际Msrp含税(), msrp));
                    } else if (org.doubleValue() > current.doubleValue()) {
                        //获得之前值比当前多余部分
                        BigDecimal msrp = NumberUtils.subtract(org, current);
                        updateStockMsrp(stocks, NumberUtils.subtract(stocks.get实际Msrp含税(), msrp));
                    }
                }
                break;
            case Constants.METHOD_TYPE_DELETE://删除(current 传入的是detail中的实际值)
                Lsh库存表Model stock = stockRepository.findLshStockByStockId(stockId);
                if (null != stock) {
                    updateStockMsrp(stock,NumberUtils.subtract(stock.get实际Msrp含税(),current));
                }
                break;
        }
    }

    /**
     * 更新msrp
     * @param stock
     * @param msrp
     * @throws Exception
     */
    private void updateStockMsrp( Lsh库存表Model stock,BigDecimal msrp)  throws  Exception{
        stock.set实际Msrp含税(msrp);
        stockRepository.save(stock);
    }

    /**
     * 构建预装精品实体
     * @param customList
     * @return
     */
    private  List<QuoteAfterSalesInfo> buildCurList(List<Map<String,String>> customList,String permit){
        List<QuoteAfterSalesInfo> list = new ArrayList<QuoteAfterSalesInfo>();
        for (int i = 0;i < customList.size(); i ++){
            //根据预装中的产品编号调用中间API获取精品详情(折扣、msrp，实际msrp从预装中取得)，单个调取组成数组
            Map<String,String> cusMap = customList.get(i);
            String proNum = cusMap.get("productNum");
            //从中间映射表获取子公司编码
            PermitCodeModel model = afterMarketService.getCompanyCode(permit);
            AfterMarketObj afterMarketObj = afterMarketService.GetAfterMarketInfoFromOther(null ==model?"2001":model.getCode(), null, proNum, null, null, null, null, null, 1, 1);
            if (afterMarketObj != null && afterMarketObj.getRows() != null && !afterMarketObj.getRows().isEmpty()) {
                for (AfterMarketRows afterMarketRows : afterMarketObj.getRows()) {
                    list.add(GetSingleCollectibleFromGroup(afterMarketRows,cusMap));
                }
            }
        }
      return list;
    }

    /**
     * GetSingleCollectible 将第三方精品转换成本地格式
     *
     * @param afterMarketRows
     * @return
     */
    private static QuoteAfterSalesInfo GetSingleCollectibleFromGroup(AfterMarketRows afterMarketRows,Map<String,String> cusMap) {
        QuoteAfterSalesInfo quoteAfterSalesInfo = new QuoteAfterSalesInfo();
        if (afterMarketRows != null) {
            ArrayList<String> listId = new ArrayList<>(),
                    listPrice = new ArrayList<>(),
                    listName = new ArrayList<>(),
                    listNum = new ArrayList<>();
            listId.add(afterMarketRows.getShopId());
            listPrice.add(afterMarketRows.getSalePrice());
            listName.add(afterMarketRows.getShopName());
            listNum.add("1");
            String priceFat = String.valueOf(cusMap.get("netReceipts"));
            String price = String.valueOf(cusMap.get("receivable"));
            String count = String.valueOf(cusMap.get("boutiqueNum"));
            quoteAfterSalesInfo = new QuoteAfterSalesInfo(afterMarketRows.getShopId(), afterMarketRows.getShopName(),
                    price, null, priceFat,
                    null, null, null, null, null, null, "0", "无", listId, listPrice, listName, listNum, "有效", null, null);
            quoteAfterSalesInfo.setOriginType("1");
            quoteAfterSalesInfo.setOriginShopUnit(afterMarketRows.getUnit());
            quoteAfterSalesInfo.setEdit("0");
            quoteAfterSalesInfo.setCollectibleCount(count);
            if (!Strings.isNullOrEmpty(afterMarketRows.getSort())) {
                quoteAfterSalesInfo.setOriginShopType(afterMarketRows.getSort().substring(0,1));
            }
        }
        return quoteAfterSalesInfo;
    }

}
